package com.ruoyi.demo.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.common.websocket.WebSocketService;
import com.ruoyi.demo.service.ITestWebSocketService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @作者：xie
 * @时间：2022/9/18 23:03
 */
@Component
public class TestWebSocketServiceImpl implements ITestWebSocketService {


    /**
     * 通过 websocket 发送消息到客户端
     *
     * @param userNames    用户名集合
     * @param title        消息标题
     * @param content      消息内容
     * @param sendUserName 发送人
     */
    @Async
    @Override
    public void sendMessageByWebSocket(List<String> userNames, String title, String content, String sendUserName) {
//        log.info("sendMessageByWebSocket");
        // 筛选在线用户
        List<String> names = new ArrayList<>();
        // 获取所有登录用户
        Collection<String> keys = RedisUtils.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        keys.forEach(key -> {
            LoginUser loginUser = RedisUtils.getCacheObject(key);
            if (ObjectUtil.isNotNull(loginUser)) {
                // 匹配登录用户企业
                if (userNames.contains(loginUser.getUsername())) {
                    names.add(loginUser.getUsername());
                }
            }
        });

        // 发送消息
        JSONObject jsonObject = new JSONObject();
        jsonObject.putOpt("title", title);
        jsonObject.putOpt("content", content);
        jsonObject.putOpt("from", sendUserName);
        WebSocketService.sendMessageBatch(names, jsonObject.toString());
    }
}
